const enums = require('../enums')
const userService = require('../services/userService')
const response = require('../utils/response')
const { getFileFromCtx, imgResize } = require('../utils/file')
const inspirecloud = require('@byteinspire/api')
const fs = require('fs')
const config = require('dotenv').config()

class UserController {
  async register(ctx) {
    const { username, password } = ctx.request.body
    const code = await userService.regiser({
      username,
      password,
    })
    if (code === enums.SUCCESS) {
      response.Success(ctx)
      return
    }
    response.FailWithCode(ctx, code, '用户名已被注册')
    return
  }
  async login(ctx) {
    const { username, password } = ctx.request.body
    const { code, data } = await userService.login({
      username,
      password,
    })
    return {
      code,
      userKey: username,
      data,
    }
  }
  async get(ctx) {
    ctx.body = ctx.user.data
  }
  // 设置个人信息
  async set(ctx) {}
  // 设置头像
  async setAvatar(ctx) {
    if (ctx.request.files && ctx.request.files.file) {
      // console.log(ctx.request.files.file)
      // imgResize(ctx.request.files.file.path)
      const file = fs.readFileSync(ctx.request.files.file.path)
      const res = await inspirecloud.file.upload(
        ctx.request.files.file.name,
        file,
        {
          token: config.parsed.FILE_TOKEN,
        }
      )
      await userService.setAvatar(ctx.user.data._id, res.url)
      response.Success(ctx)
    }
  }
}

module.exports = new UserController()
